#include "imagefilter.h"
ImageFilter::ImageFilter() {}

Mat ImageFilter::edge(Mat image)
{
    Mat dst(image.size(),image.type());
    cv::cvtColor(image,dst,cv::COLOR_BGR2GRAY);
    GaussianBlur(dst,dst,Size(5,5),0);
    Canny(dst,dst,100,200);
    // cv::cvtColor(image,dst,cv::COLOR_HSV2RGB);
    return dst;
}

Mat ImageFilter::blur(Mat image)
{
    Mat dst;
    cv::blur(image,dst,Size(15,15));
    return dst;
}

Mat ImageFilter::sharp(Mat image)
{
    Mat dst;
    // 定义卷积核
    Mat kernel = (Mat_<float>(3,3) << 0, -1, 0,
                  -1, 5, -1,
                  0, -1, 0);
    cv::filter2D(image,dst,-1,kernel);
    return dst;
}

Mat ImageFilter::bifilter(Mat image)
{
    Mat dst;
    cv::bilateralFilter(image,dst,0,30,15);
    return dst;
}

Mat ImageFilter::relief(Mat image, int Degree)
{
    Mat dst;
    cvtColor(image,dst,COLOR_BGR2GRAY);
    int w = dst.cols;
    int h = dst.rows;

    Mat img1 = Mat::zeros(dst.size(),dst.type());
    for(int i = 0;i<h;i++){
        for(int j=0;j<w-1;j++){
            // 前一个像素值
            int a = static_cast<int>(dst.at<uchar>(i, j));
            // 后一个像素值
            int b = static_cast<int>(dst.at<uchar>(i, j + 1));
            // 计算新的像素值，并确保在 0 到 255 之间
            int newValue = min(max(a - b + Degree, 0), 255);
            // 更新输出图像
            img1.at<uchar>(i, j) = static_cast<uchar>(newValue);
        }
    }
    return img1;
}

Mat ImageFilter::sketch(Mat image)
{
    Mat dst(image.size(),image.type());
    cv::cvtColor(image,dst,cv::COLOR_BGR2GRAY);
    GaussianBlur(dst,dst,Size(3,3),0);
    Canny(dst,dst,50,140);
    cv::threshold(dst,dst,90,255,THRESH_BINARY_INV);
    return dst;
}

Mat ImageFilter::nostalgia(Mat image)
{
    // 获取图像属性
    int h = image.rows;
    int w = image.cols;

    // 定义空白图像，存放怀旧处理后的图像
    Mat dst(h, w, CV_8UC3);

    // 遍历图像像素进行怀旧处理
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            float B = 0.131 * image.at<Vec3b>(i, j)[0] + 0.534 * image.at<Vec3b>(i, j)[1] + 0.272 * image.at<Vec3b>(i, j)[2];
            float G = 0.168 * image.at<Vec3b>(i, j)[0] + 0.686 * image.at<Vec3b>(i, j)[1] + 0.349 * image.at<Vec3b>(i, j)[2];
            float R = 0.189 * image.at<Vec3b>(i, j)[0] + 0.769 * image.at<Vec3b>(i, j)[1] + 0.393 * image.at<Vec3b>(i, j)[2];

            // 防止图像溢出
            if (B > 255) B = 255;
            if (G > 255) G = 255;
            if (R > 255) R = 255;

            // 设置怀旧后的像素值
            dst.at<Vec3b>(i, j)[0] = static_cast<uchar>(B);
            dst.at<Vec3b>(i, j)[1] = static_cast<uchar>(G);
            dst.at<Vec3b>(i, j)[2] = static_cast<uchar>(R);
        }
    }

    return dst;
}

Mat ImageFilter::stylization(Mat image)
{
    Mat dst(image.size(),image.type());
    cv::stylization(image,dst,60,0.6);
    return dst;
}
